package com.jd.opendj.api;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.jd.opendj.api.util.SignUtils;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>Param</p>
 * description
 *
 * @author 邓峰峰
 * @date 2019/12/13 18:38
 */
interface AbstractParam {

    String format = "json";
    String v = "1.0";
    default String toJsonString(){
        final Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        return gson.toJson(this);
    }

    /**
     * 创建请求参数
     * @param appKey
     * @param secret
     * @param token
     * @return
     */
    default Map<String,String> createParams(String appKey,String secret,String token) {
        Date timestamp = new Date();

        // 计算签名实体
        String jdParamJson = this.toJsonString();
        // 请求参数实体
        Map<String, String> param = new HashMap<>(7);
        param.put("token", token);
        param.put("app_key", appKey);
        param.put("timestamp", DateFormatUtils.format(timestamp, "yyyy-MM-dd HH:mm:ss"));
        param.put("format", format);
        param.put("v", v);
        param.put("jd_param_json", jdParamJson);
        String sign = null;
        try {
            sign = SignUtils.getSignByMD5(param, secret);
        } catch (Exception e) {
            e.printStackTrace();
        }
        param.put("sign", sign);
        return param;
    }

}
